﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using System.Text.RegularExpressions;
using System.Web;
using Newtonsoft.Json.Linq;
using System.Xml.Linq;

namespace SweetWeather
{
    public class WeatherInfoManager
    {
        /// <summary>
        /// 查询实况天气信息
        /// </summary>
        /// <param name="CityID"></param>
        /// <returns></returns>
        public static RealTimeWeather GetRealTimeWeather(string CityID)
        {
            String url = String.Format("http://www.weather.com.cn/data/sk/{0}.html", CityID);
            var result = IPManager.GetWebResponseString(url, Encoding.UTF8);
            result = GetJsonContent(result);
            RealTimeWeather info = JsonConvert.DeserializeObject<RealTimeWeather>(result);
            info.tempmargin = info.temp.Length == 1 ? "40,20,0,0" : "20,20,0,0";
            info.celsiusTextFontSize = info.temp.Length == 3 ? "140" : "170";
            info.celsiusFontSize = info.temp.Length == 3 ? "50" : "100";
            return info;
        }

        /// <summary>
        /// 查询今天天气情况
        /// </summary>
        /// <param name="CityID"></param>
        /// <returns></returns>
        public static TodayWeather GetTodayWeather(string CityID)
        {
            String url = String.Format("http://www.weather.com.cn/data/cityinfo/{0}.html", CityID);
            var result = IPManager.GetWebResponseString(url, Encoding.UTF8);
            result = GetJsonContent(result);
            TodayWeather info = JsonConvert.DeserializeObject<TodayWeather>(result);
            return info;
        }

        /// <summary>
        /// 查询最近五天天气情况
        /// </summary>
        /// <param name="CityID"></param>
        /// <returns></returns>
        public static WeatherInfoModel GetMoredayWeather(string CityID)
        {
            XElement element = XElement.Load(System.AppDomain.CurrentDomain.BaseDirectory + "Data\\Calendar.xml");
            String url = String.Format("http://m.weather.com.cn/data/{0}.html", CityID);
            var result = IPManager.GetWebResponseString(url, Encoding.UTF8);
            result = GetJsonContent(result);
            WeatherInfoModel info = JsonConvert.DeserializeObject<WeatherInfoModel>(result);
            info.img1 = setImageSource(info.img1);
            info.img3 = setImageSource(info.img3);
            info.img5 = setImageSource(info.img5);
            info.img7 = setImageSource(info.img7);
            info.img9 = setImageSource(info.img9);
            info.img11 = setImageSource(info.img11);
            var dateTm = DateTime.Now;
            DateTime.TryParse(info.date_y, out dateTm);
            info.week2 = dateTm.AddDays(1).ToString("dddd");
            info.week3 = dateTm.AddDays(2).ToString("dddd");
            info.week4 = dateTm.AddDays(3).ToString("dddd");
            info.week5 = dateTm.AddDays(4).ToString("dddd");
            info.week6 = dateTm.AddDays(5).ToString("dddd");
            //添加至数据文件
            var rs = (from elements in element.Elements("Day")
                      where DateTime.Parse(elements.Attribute("Name").Value) >= DateTime.Parse(info.date_y)
                          && DateTime.Parse(elements.Attribute("Name").Value) <= DateTime.Parse(info.date_y).AddDays(5)
                      select elements).ToList();
            //遍历6天数据
            for (int i = 1; i <= 6; i++)
            {
                var data = dateTm.AddDays(i).ToString("yyyy-MM-dd");
                var weatherName = info.weather1;
                var sheshidu = info.temp1;
                switch (i)
                {
                    case 2:
                        weatherName = info.weather2;
                        sheshidu = info.temp2;
                        break;
                    case 3:
                        weatherName = info.weather3;
                        sheshidu = info.temp3;
                        break;
                    case 4:
                        weatherName = info.weather4;
                        sheshidu = info.temp4;
                        break;
                    case 5:
                        weatherName = info.weather5;
                        sheshidu = info.temp5;
                        break;
                    case 6:
                        weatherName = info.weather6;
                        sheshidu = info.temp6;
                        break;
                }

                var ele = rs != null && rs.Count > 0 ? rs.Where(t => t.Attribute("Name").Value == data).FirstOrDefault() : null;
                var nodeText = (weatherName + " " + sheshidu).Replace('~', '/').Replace("℃", "") + "℃";
                if (ele != null)
                    ele.Value = nodeText;
                else
                {
                    XElement xele = element.Element("Day");
                    var node = new XElement("Day", new XAttribute("Name", data), nodeText);
                    if (xele != null)
                        xele.AddAfterSelf(node);
                    else
                        element.Add(node);
                }
            }
            element.Save(System.AppDomain.CurrentDomain.BaseDirectory + "Data\\Calendar.xml");
            return info;
        }

        /// <summary>
        /// 查询十四天天气情况
        /// </summary>
        /// <param name="cityName"></param>
        /// <returns></returns>
        public static MoreDayWeatherInfoAll GetFourteenDayWeather(string cityName)
        {
            try
            {
                XElement element = XElement.Load(System.AppDomain.CurrentDomain.BaseDirectory + "Data\\Calendar.xml");

                cityName = HttpUtility.UrlEncode(cityName);
                String url = String.Format("http://www.tianqiyubao.com/api/api.php?key=b9d82e567143625374be44e45ae6515b&action=moreday&search={0}&dnum=14", cityName);
                var rs = IPManager.GetWebResponseString(url, Encoding.UTF8);
                MoreDayWeatherInfoAll info = JsonConvert.DeserializeObject<MoreDayWeatherInfoAll>(rs);
                var data = info.data[0];
                var result = (from elements in element.Elements("Day")
                              where DateTime.Parse(elements.Attribute("Name").Value) >= DateTime.Parse(data[0].date)
                              && DateTime.Parse(elements.Attribute("Name").Value) <= DateTime.Parse(data[data.Count - 1].date)
                              select elements).ToList();
                //遍历14天数据
                foreach (var item in data)
                {
                    var ele = result != null && result.Count > 0 ? result.Where(t => t.Attribute("Name").Value == item.date).FirstOrDefault() : null;
                    var nodeText = item.weather_name + " " + item.tem_min + "/" + item.tem_max + "℃";
                    if (ele != null)
                        ele.Value = nodeText;
                    else
                    {
                        XElement xele = element.Element("Day");
                        var node = new XElement("Day", new XAttribute("Name", item.date), nodeText);
                        if (xele != null)
                            xele.AddAfterSelf(node);
                        else
                            element.Add(node);
                    }
                }
                element.Save(System.AppDomain.CurrentDomain.BaseDirectory + "Data\\Calendar.xml");
                return info;
            }
            catch (Exception)
            {
                return null;
            }

        }

        /// <summary>
        /// 设置图片路径
        /// </summary>
        /// <param name="imagename"></param>
        /// <returns></returns>
        private static string setImageSource(string imagename)
        {
            return "../images/weatherico/" + imagename + ".png";
        }

        /// <summary>
        /// 获取天气查询结果里面的JSON内容
        /// </summary>
        /// <param name="weatherQueryResult">天气查询结果</param>
        /// <returns></returns>
        private static String GetJsonContent(String weatherQueryResult)
        {
            string pattern = "{\"weatherinfo\":(.*)}";
            var result = Regex.Match(weatherQueryResult, pattern, RegexOptions.IgnoreCase).Groups;
            if (result.Count > 1)
            {
                return result[1].Value;
            }
            return string.Empty;
        }
    }
}
